package com.ebupt.migu.music.pubBroadcast.service.impl;


import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.ReqestParamUtil;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.BroadcastTagVo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.BroadcastTagsPo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.CreatePolicyBo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.FeeServicePo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.PkgServicePo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.PlayListTagVo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.StoreTagVo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.TagInfoBo;
import com.ebupt.migu.music.pubBroadcast.entity.createPolicy.TagInfoPo;
import com.ebupt.migu.music.pubBroadcast.entity.policyList.BroadcastActivityInfoVo;
import com.ebupt.migu.music.pubBroadcast.entity.policyList.PolicyInfoBo;
import com.ebupt.migu.music.pubBroadcast.mapper.CreatePolicyMapper;
import com.ebupt.migu.music.pubBroadcast.mapper.PolicyListMapper;
import com.ebupt.migu.music.pubBroadcast.service.CreatePolicyService;
import com.ebupt.migu.music.system.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CreatePolicyServiceImpl implements CreatePolicyService {

    @Autowired
    private CreatePolicyMapper createPolicyMapper;

    @Autowired
    private PolicyListMapper policyListMapper;

    // 文件默认保存路径
    @Value("${path.file_upload}")
    private String FILE_UPLOAD_PATH;

    @Resource
    private HttpServletRequest request;

    /**
     * 获取1级 2级标签
     * @return
     */
    @Override
    public ResultObject primaryAndSecondTag() {
        ResultObject res = new ResultObject();
        Map<String,Object> resultMap = new HashMap<>();
        //店铺的标签
        List<StoreTagVo> storeTags = createPolicyMapper.storeTag();
        //获取店铺一级标签
        List<StoreTagVo> storePrimary = storeTags.stream().filter(e -> "null".equals(e.getTagPid())).collect(Collectors.toList());
        //获取店铺二级标签
        for (int i=0;i<storePrimary.size();i++){
            StoreTagVo vo = storePrimary.get(i);
            List<StoreTagVo> storeSecond = storeTags.stream().filter(e -> e.getTagPid().equals(vo.getTagId())).collect(Collectors.toList());
            if (storeSecond !=null && storeSecond.size()>0){
                storePrimary.get(i).setStoreTagVos(storeSecond);
            }
        }
        resultMap.put("storeTag",storePrimary);
        //音乐馆标签
        List<PlayListTagVo> playListTags = createPolicyMapper.playListTags();
        //获取音乐馆一级标签
        List<PlayListTagVo> playListPrimary = playListTags.stream().filter(e -> null == e.getParentTagId()).collect(Collectors.toList());
        PlayListTagVo playListTagVo = playListPrimary.get(0);
        playListPrimary =  playListTags.stream().filter(e -> playListTagVo.getTagId().equals(e.getParentTagId()) ).collect(Collectors.toList());
        //获取音乐馆二级标签
        for (int i=0;i<playListPrimary.size();i++){
            PlayListTagVo vo = playListPrimary.get(i);
            List<PlayListTagVo> playListSecond =  playListTags.stream().filter(e -> vo.getTagId().equals(e.getParentTagId())).collect(Collectors.toList());
            if (playListSecond !=null && playListSecond.size()>0){
                playListPrimary.get(i).setPlayListTagVos(playListSecond);
            }
        }
        resultMap.put("playListTag",playListPrimary);
        //语音播报标签
        List<BroadcastTagsPo> broadcastTags = createPolicyMapper.broadcastTags();
        resultMap.put("broadcastTag",broadcastTags);
        //套餐标签
        //业务
        List<PkgServicePo> pkgService = createPolicyMapper.pkgService();
        resultMap.put("pkgService",pkgService);
        //资费
        List<FeeServicePo> feeService = createPolicyMapper.feeService();
        resultMap.put("feeService",feeService);
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        res.setData(resultMap);
        return res;
    }

    /**
     * 音乐馆、店铺根据父标签ID获取子标签或者根据标签ID 获取标签
     * @return
     */
    @Override
    public ResultObject tagInfo(TagInfoBo tagInfoBo) {
        ResultObject res = new ResultObject();
        List<TagInfoPo> tagInfoVos  = createPolicyMapper.tagInfo(tagInfoBo);
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        res.setData(tagInfoVos);
        return res;
    }

    /**
     * 文件上传
     *
     * @param fileToUpload
     * @return
     */
    @Override
    public ResultObject uploadCSVFile(MultipartFile fileToUpload) {
        ResultObject<Map<String, Object>> res = new ResultObject<>();
        // 校验文件是否为空，格式是否正常
        boolean isCSVFile = CSVUtils.validateUploadFile(fileToUpload, "csv");
        if (!isCSVFile) {
            throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
        }
        // 获取原始文件名
        String oriName = fileToUpload.getOriginalFilename();
        Date date = new Date();
        // 重命名
        String reName = FILE_UPLOAD_PATH + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS) + ".csv";
        //直接保存到指定目录
        CSVUtils.upload(fileToUpload, reName);
        List<String[]> strings = CSVUtils.csvRead(reName);
        Map<String, Object> map = new HashMap<>(4);
        map.put("reName", reName);
        map.put("oriName", oriName);
        map.put("ftpDir", FILE_UPLOAD_PATH);
        map.put("num",strings == null?0:strings.size());
        res.setMsg("文件上传成功！");
        res.setData(map);
        return res;
    }

    /**
     * 策略配置-运营歌单标签 或者 语音播报分类查询
     * @return
     */
    @Override
    public ResultObject policyMusicOrRadio() {
        Map<String,Object> resultMap = new HashMap<>();
        //音乐馆标签
        List<PlayListTagVo> playListTags = createPolicyMapper.playListTags();
        //获取音乐馆一级标签
        List<PlayListTagVo> playListPrimary = playListTags.stream().filter(e -> null == e.getParentTagId()).collect(Collectors.toList());
        PlayListTagVo playListTagVo = playListPrimary.get(0);
        playListTagVo = musicTags(playListTags,playListTagVo);
        resultMap.put("playListTag",playListTagVo);
        //语音播报标签
        List<BroadcastTagsPo> broadcastTags = createPolicyMapper.broadcastTags();
        resultMap.put("broadcastTag",broadcastTags);
        ResultObject res = new ResultObject();
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        res.setData(resultMap);
        return res;
    }

    private PlayListTagVo musicTags(List<PlayListTagVo> playListTags,PlayListTagVo playListTagVo){
        List<PlayListTagVo> playListPrimary =  playListTags.stream().filter(e -> playListTagVo.getTagId().equals(e.getParentTagId()) ).collect(Collectors.toList());
        if (playListPrimary !=null && playListPrimary.size()>0){
            for (int i=0;i<playListPrimary.size();i++){
                PlayListTagVo vo = playListPrimary.get(i);
                musicTags(playListTags,vo);
            }
        }else {
            playListPrimary = null;
        }
        playListTagVo.setPlayListTagVos(playListPrimary);
        return playListTagVo;
    }

    /**
     * 创建公播平台策略
     * @param createPolicyBo
     * @return
     */
    @Override
    @Transactional(rollbackFor = MyException.class)
    public ResultObject createPolicy(CreatePolicyBo createPolicyBo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        // 当前时间
        Date now = null;
        try{
            now = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
        }catch (Exception e){
            log.error("日期转换失败:"+e.getMessage());
            e.printStackTrace();
            throw new MyException(StatusEnum.ERROR, "日期转换失败:"+e.getMessage());
        }
        String activityId = createPolicyBo.getActivityId();
        //策略ID
        String id = null;
        if (StringUtils.isBlank(activityId)){
            id = "PB"+DateUtil.parseDateToStr(new Date(),DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS);
            createPolicyBo.setCreateTime(now);
        }else {
            //编辑
            id = activityId;
            //查询以前的数据
            PolicyInfoBo policyInfoBo = new PolicyInfoBo();
            policyInfoBo.setActivityId(activityId);
            BroadcastActivityInfoVo broadcastActivityInfoVo = policyListMapper.broadcastActivityInfo(policyInfoBo);
            String activityStatus = broadcastActivityInfoVo.getActivityStatus();
            if ("1".equals(activityStatus)){
                throw new MyException(StatusEnum.ERROR, "进行中和暂停中的策略，无法编辑！");
            }
            //删除以前的数据
            createPolicyMapper.deleteOldPolicyData(activityId);
            createPolicyBo.setCreateTime(broadcastActivityInfoVo.getCreateTime());
        }
        createPolicyBo.setActivityId(id);
        createPolicyBo.setActivityStatus("0");
        createPolicyBo.setPause("0");
        SysUser user = ReqestParamUtil.userInfo(request);
        createPolicyBo.setCreatorId(user.getLoginName());
        createPolicyBo.setCreatorName(user.getUserName());
        createPolicyBo.setCreatorDepartment(user.getDeptId());
        createPolicyBo.setCreatorDepartmentName(user.getDeptName());
        createPolicyBo.setModifyTime(now);
        //客群类型：1-标签客群；2-文件上传【商户ID】；3-手工录入【商户ID】
        String customerType = createPolicyBo.getCustomerType();
        if ("1".equals(customerType)){
            //公播平台标签客群
            createPolicyBo.setCustomerStatus("1");
            List<BroadcastTagVo> broadcastTags = createPolicyBo.getBroadcastTags();
            if (broadcastTags !=null && broadcastTags.size()>0){
                createPolicyMapper.batchBroadcastTags(broadcastTags,id);
            }else{
                createPolicyBo.setCustomerType("4");
            }

        }else if ("2".equals(customerType)){
            //公播平台文件导入客群
            createPolicyBo.setCustomerStatus("0");
            createPolicyMapper.broadcastCustomerFile(createPolicyBo);
        }else if ("3".equals(customerType)){
            //公播平台手工录入客群
            createPolicyBo.setCustomerStatus("0");
            String storeIds = createPolicyBo.getStoreIds();
            if (!StringUtils.isBlank(storeIds)){
                List<String> list = Arrays.asList(storeIds.split("\\|"));
                createPolicyMapper.broadcastCustomerInput(list,id);
            }

        }
        //运营触点：1-Banner；2-歌单广场；3-语音播报
        String activityType = createPolicyBo.getActivityType();
        if ("1".equals(activityType)){
            //banner
            createPolicyMapper.broadcastBannerInfo(createPolicyBo);
        }else if ("2".equals(activityType)){
            //歌单广场
            createPolicyMapper.broadcastPlaylistInfo(createPolicyBo);
        }else if ("3".equals(activityType)){
            //语音播报
            createPolicyMapper.broadcastRadioInfo(createPolicyBo);
        }
        //公播平台活动详情插入数据
        createPolicyMapper.broadcastActivityInfo(createPolicyBo);
        ResultObject res = new ResultObject();
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        return res;
    }
}
